﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;

namespace SearchAggregator
{
    public static class SearchEngineHelper
    {
        private static readonly HttpClient client = new HttpClient();

        static SearchEngineHelper()
        {
            //client.DefaultRequestHeaders.Add("User-Agent",
            //    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
            //    "(KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36");
        }

        public static async Task<string> SearchSoAsync(string keyword)
        {
            try
            {
                string url = $"https://www.so.com/s?q={Uri.EscapeDataString(keyword)}";
                string html = await client.GetStringAsync(url);
                return ExtractFromSo(html); 
            }
            catch (Exception ex)
            {
                return $"百度 搜索失败：{ex.Message}";
            }
        }

        public static async Task<string> SearchBingAsync(string keyword)
        {
            try
            {
                string url = $"https://www.bing.com/search?q={Uri.EscapeDataString(keyword)}";
                string html = await client.GetStringAsync(url);
                return ExtractFromBing(html);
            }
            catch (Exception ex)
            {
                return $"Bing 搜索失败：{ex.Message}";
            }
        }

        private static string ExtractFromBaidu(string html)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(html);

            var sb = new StringBuilder();

      
            var aiParagraphs = doc.DocumentNode.SelectNodes("//p[contains(@class, 'marklang-paragraph')]");
            if (aiParagraphs != null)
            {
                foreach (var node in aiParagraphs)
                {
                    string text = HtmlEntity.DeEntitize(node.InnerText.Trim());
                    if (!string.IsNullOrWhiteSpace(text))
                        sb.AppendLine(text);
                    if (sb.Length > 200) break;
                }
            }

            if (sb.Length < 100)
            {
                var legacy = doc.DocumentNode.SelectNodes("//div[contains(@class, 'c-abstract') or contains(@class, 'c-span18') or contains(@class, 'c-line-clamp3')]");
                if (legacy != null)
                {
                    var added = new HashSet<string>();
                    foreach (var node in legacy)
                    {
                        string text = HtmlEntity.DeEntitize(node.InnerText.Trim());
                        if (!string.IsNullOrWhiteSpace(text) && added.Add(text))
                            sb.AppendLine(text);
                        if (sb.Length > 200) break;
                    }
                }
            }

            // 3. 截断为前 200 字，优先按句号
            string result = sb.ToString().Trim();
            if (result.Length > 200)
            {
                int cut = result.LastIndexOfAny(new[] { '。', '！', '？', '.', '!', '?' }, 200);
                if (cut > 50)
                    result = result.Substring(0, cut + 1);
                else
                    result = result.Substring(0, 200);
            }

            return "百度结果摘要：\n" + (string.IsNullOrWhiteSpace(result) ? "未能提取到摘要内容。" : result);
        }


        private static string ExtractFromSo(string html)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(html);

            var sb = new StringBuilder();

           
            var nodes = doc.DocumentNode.SelectNodes("//li[contains(@class, 'res-list')]//p");

            if (nodes != null)
            {
                foreach (var node in nodes)
                {
                    string text = node.InnerText.Trim();
                    if (!string.IsNullOrWhiteSpace(text))
                        sb.AppendLine(text);

                    if (sb.Length > 200) break;
                }
            }

            string result = sb.ToString().Trim();
            if (result.Length > 200)
                result = result.Substring(0, 200);

            return "百度结果摘要：\n" + (string.IsNullOrWhiteSpace(result) ? "未能提取到摘要内容。" : result);
        }



        private static string ExtractFromBing(string html)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(html);

            var sb = new StringBuilder();
            var nodes = doc.DocumentNode.SelectNodes("//li[@class='b_algo']//p");

            if (nodes != null)
            {
                foreach (var node in nodes)
                {
                    string text = node.InnerText.Trim();
                    if (!string.IsNullOrWhiteSpace(text))
                        sb.AppendLine(text);
                    if (sb.Length > 200) break;
                }
            }

            string result = sb.ToString().Trim();
            if (result.Length > 200)
                result = result.Substring(0, 200);

            return "Bing结果摘要：\n" + (string.IsNullOrWhiteSpace(result) ? "未能提取到摘要内容。" : result);
        }
    }
}
